﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace EnCor.Config
{
    public class PolymorphicConfig : NameTypeConfigElement
    {
        private PolymorphicConfig _PolymorphicInstance;

        [ConfigurationProperty(Constants.Config_DataType)]
        public string DataTypeName
        {
            get
            {
                return (string)this[Constants.Config_DataType];
            }
        }

        public Type DataType
        {
            get
            {
                if (string.IsNullOrEmpty(DataTypeName))
                {
                    return this.GetType();
                }
                return Type.GetType(DataTypeName);
            }
        }

        public PolymorphicConfig PolymorphicInstance
        {
            get
            {
                return _PolymorphicInstance;
            }
        }

        protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
        {
            base.DeserializeElement(reader, serializeCollectionKey);
            if (this.GetType() == DataType)
            {
                _PolymorphicInstance = this;
            }
            else
            {
                _PolymorphicInstance = (PolymorphicConfig)Activator.CreateInstance(DataType);
                _PolymorphicInstance.DeserializeElement(reader);
            }
        }
    }
}
